"""
bing搜索引擎查询请求示例
"""
from urllib import parse
from urllib.request import urlopen, Request
import ssl

base_url = 'http://www.bing.com'

params = {'q': '春龙'}

# 1、先对请求参数编码
url = '{}?{}'.format(base_url, parse.urlencode(params))
print(url)

# 2、urlopen发送http请求
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'
request = Request(url, headers={
    'User-agent': user_agent
})

"""
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)>
通过自定义ssl._create_unverified_context()解决以上问题: 忽略不信任的证书
"""
context = ssl._create_unverified_context()
with urlopen(request, context=context) as response:
    with open('bing.html', mode='wb') as file:
        file.write(response.read())
        file.flush()
